package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.entity.UserEntity;
import com.example.teaching_server.repository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户信息查询接口")
public class UserController {

    private final UserRepository userRepository;

    /**
     * 获取用户选项（统一查询接口）
     */
    @GetMapping("/options")
    @Operation(summary = "获取用户选项", description = "根据关键字、角色和班级ID获取用户选项列表")
    public ApiResponse<List<UserOptionDTO>> getUserOptions(
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "用户角色") @RequestParam(required = false) String role,
            @Parameter(description = "班级ID") @RequestParam(required = false) Long classId) {

        log.info("开始获取用户选项: keyword={}, role={}, classId={}", keyword, role, classId);

        try {
            List<UserEntity> users;

            if (keyword != null && !keyword.trim().isEmpty()) {
                users = userRepository.findByNameContainingIgnoreCase(keyword);
            } else if (role != null && !role.trim().isEmpty()) {
                users = userRepository.findByRole(role);
            } else if (classId != null) {
                users = userRepository.findByClassId(classId);
            } else {
                users = userRepository.findAll();
            }

            // 组合条件筛选
            if (role != null && classId != null) {
                users = users.stream()
                        .filter(user -> role.equals(user.getRole()) && classId.equals(user.getClassId()))
                        .collect(Collectors.toList());
            } else if (role != null && keyword != null) {
                users = users.stream()
                        .filter(user -> role.equals(user.getRole()) &&
                                user.getName().toLowerCase().contains(keyword.toLowerCase()))
                        .collect(Collectors.toList());
            } else if (classId != null && keyword != null) {
                users = users.stream()
                        .filter(user -> classId.equals(user.getClassId()) &&
                                user.getName().toLowerCase().contains(keyword.toLowerCase()))
                        .collect(Collectors.toList());
            }

            List<UserOptionDTO> options = users.stream()
                    .map(this::convertToOptionDTO)
                    .collect(Collectors.toList());

            log.info("成功获取{}个用户选项", options.size());
            return ApiResponse.success("用户选项获取成功", options);
        } catch (Exception e) {
            log.error("获取用户选项失败", e);
            return ApiResponse.fail("获取用户选项失败: " + e.getMessage());
        }
    }

    /**
     * 按角色获取用户选项
     */
    @GetMapping("/options/by-role")
    @Operation(summary = "按角色获取用户选项", description = "根据角色获取用户选项列表")
    public ApiResponse<List<UserOptionDTO>> getUserOptionsByRole(
            @Parameter(description = "用户角色") @RequestParam String role) {

        log.info("开始按角色获取用户选项: role={}", role);

        try {
            List<UserEntity> users = userRepository.findByRole(role);
            List<UserOptionDTO> options = users.stream()
                    .map(this::convertToOptionDTO)
                    .collect(Collectors.toList());

            log.info("成功获取角色{}的{}个用户选项", role, options.size());
            return ApiResponse.success("用户选项获取成功", options);
        } catch (Exception e) {
            log.error("按角色获取用户选项失败: role={}", role, e);
            return ApiResponse.fail("获取用户选项失败: " + e.getMessage());
        }
    }

    /**
     * 按班级获取用户选项
     */
    @GetMapping("/options/by-class")
    @Operation(summary = "按班级获取用户选项", description = "根据班级ID获取用户选项列表")
    public ApiResponse<List<UserOptionDTO>> getUserOptionsByClass(
            @Parameter(description = "班级ID") @RequestParam Long classId) {

        log.info("开始按班级获取用户选项: classId={}", classId);

        try {
            List<UserEntity> users = userRepository.findByClassId(classId);
            List<UserOptionDTO> options = users.stream()
                    .map(this::convertToOptionDTO)
                    .collect(Collectors.toList());

            log.info("成功获取班级{}的{}个用户选项", classId, options.size());
            return ApiResponse.success("用户选项获取成功", options);
        } catch (Exception e) {
            log.error("按班级获取用户选项失败: classId={}", classId, e);
            return ApiResponse.fail("获取用户选项失败: " + e.getMessage());
        }
    }

    /**
     * 搜索用户
     */
    @GetMapping("/search")
    @Operation(summary = "搜索用户", description = "多条件搜索用户信息")
    public ApiResponse<List<UserOptionDTO>> searchUsers(
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "用户角色") @RequestParam(required = false) String role,
            @Parameter(description = "班级ID") @RequestParam(required = false) Long classId,
            @Parameter(description = "用户名") @RequestParam(required = false) String username) {

        log.info("开始搜索用户: keyword={}, role={}, classId={}, username={}",
                keyword, role, classId, username);

        try {
            List<UserEntity> users = userRepository.findAll();

            // 多条件筛选
            if (keyword != null && !keyword.trim().isEmpty()) {
                users = users.stream()
                        .filter(user ->
                                (user.getName() != null && user.getName().toLowerCase().contains(keyword.toLowerCase())) ||
                                        (user.getUsername() != null && user.getUsername().toLowerCase().contains(keyword.toLowerCase())))
                        .collect(Collectors.toList());
            }

            if (role != null && !role.trim().isEmpty()) {
                users = users.stream()
                        .filter(user -> role.equals(user.getRole()))
                        .collect(Collectors.toList());
            }

            if (classId != null) {
                users = users.stream()
                        .filter(user -> classId.equals(user.getClassId()))
                        .collect(Collectors.toList());
            }

            if (username != null && !username.trim().isEmpty()) {
                users = users.stream()
                        .filter(user -> username.equals(user.getUsername()))
                        .collect(Collectors.toList());
            }

            List<UserOptionDTO> options = users.stream()
                    .map(this::convertToOptionDTO)
                    .collect(Collectors.toList());

            log.info("成功搜索到{}个用户", options.size());
            return ApiResponse.success("用户搜索成功", options);
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            return ApiResponse.fail("搜索用户失败: " + e.getMessage());
        }
    }

    /**
     * 转换实体为选项DTO
     */
    private UserOptionDTO convertToOptionDTO(UserEntity user) {
        UserOptionDTO option = new UserOptionDTO();
        option.setId(user.getId());
        option.setName(user.getName());
        option.setUsername(user.getUsername());
        option.setRole(user.getRole());
        option.setDisplayName(user.getName() + " (" + user.getUsername() + ") - " + user.getRole());
        return option;
    }

    /**
     * 用户选项DTO
     */
    @Setter
    @Getter
    public static class UserOptionDTO {
        private Long id;
        private String name;
        private String username;
        private String role;
        private String displayName;

    }
}
